<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
          <el-option label="草稿" value="0"/>
          <el-option label="审核中" value="1"/>
          <el-option label="已审核" value="2"/>
          <el-option label="结项" value="3"/>
          <el-option label="已驳回" value="4"/>
        </el-select>
      </el-form-item>-->
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <el-card style="border-radius: 10px;margin-top: 15px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectInfoList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="项目编号" align="center" prop="projectCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['xm:projectInfo:query']"
          >{{ scope.row.projectCode }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="版本" align="center" prop="version"/>
      <el-table-column label="审批状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.project_info_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName"/>
      <el-table-column label="产品编码" align="center" prop="productId"/>
      <el-table-column label="产品名称" align="center" prop="productName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==1"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xm:projectInfo:examine']"
          >审批
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改项目信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="9">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="form.projectCode" :readonly="optType == 'view' || optType == 'examine'" placeholder="请输入项目编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && optType != 'examine'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" :readonly="optType == 'view' || optType == 'examine'" placeholder="请输入项目名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="版本" prop="version">
              <el-input v-model="form.version" :readonly="optType == 'view' || optType == 'examine'" placeholder="请输入版本"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户编码" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectClient"
                  icon="el-icon-search"
                  v-if="optType != 'view' || optType == 'examine'"
                >
                </el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected"></ClientSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateId">
              <el-select v-model="form.templateId" style="width: 100%" :disabled="optType  == 'view' || optType == 'examine'" clearable
                         @change="handleChange">
                <el-option
                  v-for="item in templateInfoList"
                  :key="item.id"
                  :label="item.templateName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" readonly>
                <el-button slot="append" @click="handleSelectProduct" icon="el-icon-search"
                           v-if="optType != 'view' || optType == 'examine'"></el-button>
              </el-input>
              <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" readonly placeholder="请输入规格型号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="plannedStartDate">
              <el-date-picker clearable
                              style="width: 100%;"
                              v-model="form.plannedStartDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :readonly="optType == 'view' || optType == 'examine'"
                              placeholder="请选择计划开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束日期" prop="plannedEndDate">
              <el-date-picker clearable
                              style="width: 100%;"
                              v-model="form.plannedEndDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :readonly="optType == 'view' || optType == 'examine'"
                              placeholder="请选择计划结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="立项申请人" prop="applicant">
              <el-input v-model="form.applicant" :readonly="optType == 'view' || optType == 'examine'" placeholder="请输入立项申请人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="立项申请日期" prop="applicationDate">
              <el-date-picker clearable
                              style="width: 100%;"
                              v-model="form.applicationDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :readonly="optType == 'view' || optType == 'examine'"
                              placeholder="请选择立项申请日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件" prop="fileId">
          <FileUpload
            :limit="100"
            :fileSize="100"
            :fileType="fileType"
            :value="fileList"
            optType="view"
            :isShowTip="false"
            @onUploaded="handleUploaded"
            @onRemoved="handleRemoved"
            :disabled="true"
          >
          </FileUpload>
        </el-form-item>
        <el-form-item label="审批备注">
          <el-input v-model="form.examineRemark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="optType != 'view'" @click="submitForm(true)">通 过</el-button>
        <el-button type="primary" v-if="optType != 'view'" @click="submitForm(false)">驳 回</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listProjectInfo,
  getProjectInfo,
  delProjectInfo,
  addProjectInfo,
  editStatus,
  updateProjectInfo, bgProjectInfo, examineList, examine
} from "@/api/mes/xm/projectInfo";
import {genCode} from "@/api/system/autocode/rule";
import ClientSelect from "@/components/clientSelect/single.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import {treeSelect, listAll} from "@/api/mes/xm/templateInfo";
import ProjectUser from "@/views/mes/xm/projectUser/index.vue";
import ItemInfo from "@/views/mes/xm/itemInfo/index.vue";
import {getPermissions} from "@/api/mes/xm/projectUser";

export default {
  name: "ProjectInfo",
  dicts: ['project_info_status'],
  components: {ProjectUser, ItemSelect, ClientSelect, ItemInfo},
  data() {
    return {
      nowTemplateId: "",
      nowTemplateName: "",
      activeName: 'first',
      allDataListOne: [],
      dataOptions: null,
      dataList: [],
      dataListOne: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      editTitle: "",
      editOpen: false,
      fileType: [
        // 文档类
        "pdf", "doc", "docx", "xls", "xlsx",
        // 图片类
        "jpg", "jpeg", "png", "gif", "bmp",
        // 视频类
        "mp4", "avi", "rmvb", "mkv", "mov",
        // 压缩文件类
        "zip", "rar", "7z", "tar", "gz"
      ],
      permissionsList: [],
      showInoutAdd: false,
      fileList: [],
      fileListBg:[],
      optType: null,
      inoptType: null,
      autoGenFlag: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目信息表格数据
      projectInfoList: [],
      // 弹出层标题
      title: "",
      bgtitle: "",
      bgopen: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null, status: null, customerName: null, productName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectCode: [
          {required: true, message: "项目编号不能为空", trigger: "blur"}
        ], projectName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ], templateId: [
          {required: true, message: "请选择项目模板", trigger: "blur"}
        ],bgCode:[
          {required: true, message: "变更申请编号不能为空", trigger: "blur"}
        ]
      },

      templateInfoList: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleClick(tab, event) {
      this.getPermissions();
      console.log(tab, event);
    },
    // 获取图纸分类树
    getTreeSelect(id) {
      treeSelect(id).then(response => {
        this.dataOptions = response.data.tree;
        this.dataList = response.data.list;
        this.findItemById(this.dataList, id);
      })
    },
    editCancel() {
      this.editOpen = false;
      this.dataOptions = [];
      this.dataList = [];
      this.dataListOne = [];
      this.allDataListOne = []
    },
    bgcancel() {
      this.bgopen = false;
      this.reset();
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.nowTemplateId = data.id;
      this.nowTemplateName = data.label;
      if (this.permissionsList.includes(this.form.templateId)) {
        this.showInoutAdd = true;
      } else {
        this.showInoutAdd = this.permissionsList.includes(this.nowTemplateId);
      }
    },
    //点击编号

    handleView(row) {
      this.reset();
      this.getTemplateInfoList();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {
        this.form = response.data;
        this.nowTemplateId = this.form.templateId;
        this.nowTemplateName = this.form.templateName;
        this.fileList.push(response.data.fileId);
        this.open = true;
        this.optType = 'view';
        this.inoptType = 'view';
        //this.getTreeSelect(this.form.templateId);
        this.title = "项目信息";
        this.showInoutAdd = false;
      });
    },
    getPermissions() {
      getPermissions().then(response => {
        this.permissionsList = response.data;
        if (this.permissionsList.includes(this.form.templateId)) {
          this.showInoutAdd = true;
        } else {
          this.showInoutAdd = this.permissionsList.includes(this.nowTemplateId);
        }
      })
    },
    handleChange(val) {
      this.form.templateName = this.templateInfoList.find(item => item.id == val).templateName;
    },
    getTemplateInfoList() {
      listAll().then(response => {
        this.templateInfoList = response.data;
      });
    },
    // 上传成功回调
    handleUploaded(data) {
      this.form.fileId = data;
    },
    // 删除成功回调
    handleRemoved(data) {
      this.form.fileId = data;
    },
    // 上传成功回调
    handleUploadedBg(data) {
      this.form.bgFileId = data;
    },
    // 删除成功回调
    handleRemovedBg(data) {
      this.form.bgFileId = data;
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    // 产品物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.productId = obj.itemCode;
        this.form.productName = obj.itemName;
        this.form.specification = obj.specification;
      }
    },
    //客户选择弹出框
    onClientSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.customerId = obj.clientId;
        this.form.customerName = obj.clientName;
      }
    },
    handleSelectClient() {
      this.$refs.clientSelect.showFlag = true;
    },
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('XM_PROJECT_CODE').then(response => {
          this.form.projectCode = response;
        });
      } else {
        this.form.projectCode = null;
      }
    },
    handleAutoGenChangeBg(autoGenFlag) {
      if (autoGenFlag) {
        genCode('XM_CHANGE_CODE').then(response => {
          this.form.bgCode = response;
        });
      } else {
        this.form.bgCode = null;
      }
    },
    /** 查询项目信息列表 */
    getList() {
      this.loading = true;
      examineList(this.queryParams).then(response => {
        this.projectInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectCode: null,
        projectName: null,
        version: null,
        status: 0,
        customerId: null,
        customerName: null,
        productId: null,
        productName: null,
        templateId: null,
        templateName: null,
        specification: null,
        plannedStartDate: null,
        plannedEndDate: null,
        applicant: null,
        applicationDate: null,
        fileId: null,
        bgReason: null,
        bgFileId: null,
        bgCode: null,
        bgOldId: null,
        bgStatus: 0,
        bgDate: null,
        remarks: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null,
        examineRemark:null
      };
      this.fileListBg = [];
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTemplateInfoList();
      this.optType = 'add';
      this.handleAutoGenChange(true);
      this.open = true;
      this.title = "添加项目信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTemplateInfoList();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {
        this.fileList.push(response.data.fileId);
        this.form = response.data;
        this.open = true;
        this.optType = 'examine';
        this.title = "审批";
      });
    },
    handleEditStatus(row) {
      this.$modal.confirm('确认要提交完成吗？提交后不可修改。').then(function () {
        return editStatus(row.id, 1);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(function () {
        this.getList();
      });
    },

    handleProjectChangeCommit(row){
      this.$modal.confirm('确认要提交变更吗？提交后不可修改。').then(function () {
        return editStatus(row.id, 6);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(function () {
        this.getList();
      });
    },
    //维护项目信息
    handleMaintain(row) {
      this.reset();
      this.getTemplateInfoList();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {
        this.form = response.data;
        this.nowTemplateId = this.form.templateId;
        this.nowTemplateName = this.form.templateName;
        this.fileList.push(response.data.fileId);
        this.editOpen = true;
        this.optType = 'edit';
        this.inoptType = 'view';
        this.getTreeSelect(this.form.templateId);
        this.editTitle = "维护项目信息";
        this.getPermissions();
      });
    },
    handleProjectChange(row) {
      this.reset();
      this.getTemplateInfoList();
      const id = row.id || this.ids
      getProjectInfo(id).then(response => {
        this.fileListBg.push(response.data.bgFileId);
        this.form = response.data;
        if(!this.form.bgCode){
          this.handleAutoGenChangeBg(true);
        }
        this.bgopen = true;
        this.optType = 'update';
        this.bgtitle = "变更项目信息";
      });
    },
    handleComplete(row) {
      this.$modal.confirm('确认要提交结项吗？结项后不可修改。').then(function () {
        return editStatus(row.id, 3);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(function () {
        //this.getList();
      });
    },
    /** 提交按钮 */
    submitForm(flag) {
      if (flag) {
        this.form.status = 2;
      } else {
        this.form.status = 4;
      }
      var that=this;
      this.$modal.confirm('确认要提交审批吗？提交后不可修改').then(function () {
        if (that.form.id != null) {
          examine(that.form.id,that.form.status, that.form.examineRemark).then(response => {
            that.$modal.msgSuccess("审批成功");
            that.open = false;
            that.getList();
          });
        }
      }).then(() => {
        //this.$modal.msgSuccess("成功");
      }).catch(function () {

      });

    },
    /** 提交变更申请 */
    /*submitFormBg(flag) {
      if (flag) {
        this.form.status = 1;
      } else {
        this.form.status = 0;
      }
      this.$modal.confirm('确认要提交变更吗？结项后不可修改。').then(function () {
        return editStatus(row.id, 5);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(function () {
        //this.getList();
      });
    },*/
    submitFormBg(flag) {
      if (flag) {
        this.form.status = 6;
      } else {
        this.form.status = 5;
      }
      if (flag) {
        var that=this;
        this.$modal.confirm('确认要提交吗？提交后不可修改').then(function () {
          that.$refs["bgform"].validate(valid => {
            if (valid) {
              if (that.form.id != null) {
                bgProjectInfo(that.form).then(response => {
                  that.$modal.msgSuccess("申请成功");
                  that.bgopen = false;
                  that.getList();
                });
              }
            }
          });
        }).then(() => {
          //this.$modal.msgSuccess("成功");
        }).catch(function () {

        });
      } else {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              bgProjectInfo(this.form).then(response => {
                this.$modal.msgSuccess("保存成功");
                this.bgopen = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目信息编号为"' + ids + '"的数据项？').then(function () {
        return delProjectInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xm/projectInfo/export', {
        ...this.queryParams
      }, `projectInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
